import { getGoodsApi,addGoodsApi,updateGoodsApi ,delGoodsApi,searchGoodsApi} from "@/api/goods/goods";
import baseUrl from '@/config/config'
import { v4 as uuidv4 } from 'uuid';
import { useState,useEffect } from "react";
import {  Input, Button, Modal, message ,Form,Upload,Popconfirm ,Pagination } from 'antd';
import { LoadingOutlined, PlusOutlined,ReloadOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import type { PaginationProps } from 'antd';
import useStore from "@/store";
import './index.less'
const { Search } = Input;
  const tailFormItemLayout = {
    wrapperCol: {
      xs: {
        span: 24,
        offset: 0,
      },
      sm: {
        span: 16,
        offset: 16,
      },
    },
  };
  
export default function GoodsList(){
    // 定义分页的数据
    const [pageSize,setPageSize] = useState<number>(10)
    const [pageNum,setPageNum] = useState<number>(1)
    const [total,setTotal] = useState<number>(0)
    const userInfo = useStore<any>((state: any) => state.userInfo)
    // 模态框
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [modalTitle,setModalTitle] = useState('')
    // 表单
    const [form] = Form.useForm();
    const [goodsList,setGoodsList]  = useState<any>([{
            "id": 1,
            "goodsName": "洗剪吹",
            "goodsPrice": "11",
            "goodsItn": "123",
            "goodsImg": "/uploadImgs/shampoo1.jpg",
            "goodsNum": "11"
    }])
    // 上传图片
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();
   
    
  
    useEffect(()=>{
        getGoods(pageSize,pageNum)
    },[])
    const getGoods = (pageSize:number,pageNum:number)=>{
        let params = {pageSize:pageSize,pageNum:pageNum,belongToShop:userInfo.storeId}
        getGoodsApi(params).then(getGoodsRes=>{
            if(getGoodsRes.code == 200){
                setTotal(getGoodsRes.total)
                setGoodsList(getGoodsRes.goodsData)
            }
        })
    }
    const addPackageModal:any =(title:string,e:any)=>{
    //    修改商品赋值给表单
        if(e){
            setImageUrl(baseUrl.baseUrl + e.goodsImg)
            form.setFieldsValue(e)
        }
        // 添加商品
        else{
            form.setFieldsValue({id:uuidv4()})
        }
        setModalTitle(title)
        setIsModalOpen(true);
    }  
    const fresh =()=>{
        try {
            getGoods(pageSize, pageNum)
            message.open({
              type: 'success',
              content: '刷新成功',
            });
          } catch (error) {
            message.open({
              type: 'error',
              content: '刷新失败' + error,
            });
          }
    }
    const handleOk = () => {
        setIsModalOpen(false);
        form.resetFields()
        setImageUrl('')
    };

    const handleCancel = () => {
        setIsModalOpen(false);
        form.resetFields()
        setImageUrl('')
    };
    const onFinish = async (values: any) => {
        let updateParams = values
        updateParams.belongToShop = userInfo.storeId +''
        updateParams.id = values.id + ''
        if(modalTitle == '添加商品'){
            try {
               let addGoodsRes = await addGoodsApi(updateParams)
               if(addGoodsRes.code ==200){
                // 重新获取数据
                getGoods(pageSize,pageNum)
                // 关闭模态框
                handleOk()
                message.open({
                    type: 'success',
                    content: addGoodsRes.msg,
                  });
               }else{
                // 关闭模态框
                handleOk()
                message.open({
                    type: 'error',
                    content: addGoodsRes.msg,
                  });
               }
            } catch (error) {
                // 关闭模态框
                handleOk()
                message.open({
                    type: 'error',
                    content: 'error' +error,
                  });
            }
            
        }else if(modalTitle == '修改商品'){
            try {
                let updateGoodsRes = await updateGoodsApi(updateParams)
                console.log(updateGoodsRes);
                if(updateGoodsRes.code ==200){
                    // 重新获取数据
                    getGoods(pageSize,pageNum)
                    // 关闭模态框
                    handleOk()
                    message.open({
                        type: 'success',
                        content: updateGoodsRes.msg,
                      });
                   }else{
                    // 关闭模态框
                    handleOk()
                    message.open({
                        type: 'error',
                        content: updateGoodsRes.msg,
                      });
                   }
                
            } catch (error) {
                // 关闭模态框
                handleOk()
                message.open({
                    type: 'error',
                    content: 'error' +error,
                  });
            }
        }
      };
    // 上传图片方法
  
    const beforeUpload = (file: RcFile) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
      };
      const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
          setLoading(true)
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
            setLoading(false);
            setImageUrl(info.file.response.fileUrl);
            if(info.file.response.code ==200){
                form.setFieldsValue({'goodsImg':'/uploadImgs/' + info.file.response.filename})
            }
          
        }
      };
    
      const uploadButton = (
        <div>
          {loading ? <LoadingOutlined /> : <PlusOutlined />}
          <div style={{ marginTop: 8 }}>Upload</div>
        </div>
      );
    const confirm =async (item:any) =>{
        let params = { id : item.id}
        try {
           let delGoodsRes = await delGoodsApi(params)
           if(delGoodsRes.code ==200){
            // 重新获取数据
            getGoods(pageSize,pageNum)
            // 关闭模态框
            handleOk()
            message.open({
                type: 'success',
                content: delGoodsRes.msg,
              });
           }else{
            // 关闭模态框
            handleOk()
            message.open({
                type: 'error',
                content: delGoodsRes.msg,
              });
           }
        } catch (error) {
            // 关闭模态框
            handleOk()
            message.open({
                type: 'error',
                content: 'error' +error,
              });
        }
    }
    // 分页
    const onShowSizeChange: PaginationProps['onShowSizeChange'] = (current, pageSize) => {
        getGoods(pageSize,current)
      };
    const onChangePageNum:PaginationProps['onChange']  = (current, pageSize)=>{
        getGoods(pageSize,current)
      }
      // 搜索
    const search:any =  async (value:any)=>{
      if(value){
        let params = {
          keyWord:value,
          belongToShop:userInfo.storeId
        }
        try {
          let searchRes = await searchGoodsApi(params)
          if(searchRes.code == 200){
            setGoodsList(searchRes.goodsList)
            setTotal(searchRes.total)
            message.open({
              type:'success',
              content:searchRes.msg
            })
          }else{
            message.open({
              type:'success',
              content:searchRes.msg
            })
          }
        } catch (error) {
          message.open({
            type:'error',
            content:'搜索失败'+error
          })
        }
      }
      
    }
    return (
        <div>
            <div>
                <Search
                    placeholder="商品名称"
                    allowClear
                    onSearch={search}
                    enterButton="搜索"
                    style={{ width: 300 }}
                />
                <Button onClick={()=>addPackageModal('添加商品')} className='vip_btn' type="primary">
                    添加商品
                </Button>
                <Button className='vip_btn' type="primary" shape="circle" onClick={fresh} icon={<ReloadOutlined />} />
            </div>
            <div className='list_data'>
                {
                    goodsList.map((item:any) => {
                        return (
                            <li className='package' key={item.id}>
                                <img className='package_img' src={baseUrl.baseUrl +item.goodsImg} alt="" />
                                <p className='package_name'>{item.goodsName}</p>
                                <p className='package_itn'>{item.goodsItn} </p>
                                <p className='package_price'>{item.goodsPrice} ￥</p>
                                <div className="package_btn">
                                    <Button type="primary" onClick={()=>addPackageModal('修改商品',item)}>修改商品</Button>
                                    
                                    <Popconfirm
                                        title="永久删除"
                                        description="该操作无法逆转，是否继续"
                                        onConfirm={()=>confirm(item)}
                                        >
                                            <Button type="primary" danger>删除商品</Button>
                                        </Popconfirm>
                                </div>
                            </li>
                        )
                    })
                }
            </div>
          <Modal footer={null} title={modalTitle} open={isModalOpen} onOk= {handleOk} onCancel={handleCancel}>
                    <Form
                        form={form}
                        name="register"
                        onFinish={onFinish}
                        initialValues={{ residence: ['zhejiang', 'hangzhou', 'xihu'], prefix: '86' }}
                        style={{ maxWidth: 600 }}
                        scrollToFirstError
                        >
                    
                        <Form.Item
                            name="id"
                            label="商品ID"
                            rules={[{ required: true, message: '请输入商品ID' }]}
                        >
                            <Input disabled={true} />
                        </Form.Item>
                        <Form.Item
                            name="goodsName"
                            label="商品名称"
                            rules={[{ required: true, message: '请输入商品名称'}]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            name="goodsPrice"
                            label="商品价格"
                            rules={[{ required: true, message: '请输入商品价格'}]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            name="goodsItn"
                            label="商品介绍"
                            rules={[{ required: true, message: '请输入商品价格'}]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            name="goodsNum"
                            label="商品库存"
                            rules={[{ required: true, message: '请输入商品库存' }]}
                        >
                            <Input />
                        </Form.Item>
    
                        <Form.Item
                            name="goodsImg"
                            label="商品图片"
                            rules={[{ required: true, message: '请输入商品图片'}]}
                        >
                           <div>
                             <Upload
                                name="file"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action="http://localhost:3000/api/upload/uploadimg"
                                maxCount={1}
                                headers={   
                                        {
                                            'authorization': localStorage.getItem('token') || ''
                                        }
                                }
                                beforeUpload={beforeUpload}
                                onChange={handleChange}
                            >
                                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                                <Input className="dispalyNone"/>
                            </Upload>
                           </div>
                            
                        </Form.Item>
                       
                        <Form.Item {...tailFormItemLayout}>
                                <Button onClick={handleOk} style={{ marginRight: 20 }}>取消</Button>
                                <Button type="primary" htmlType="submit">
                                {modalTitle == '添加商品' ? '添加' :'修改'}
                                </Button>
                        </Form.Item>
                        </Form>
            </Modal>
            <div className="pagin">
            <Pagination
                // showSizeChanger
                onShowSizeChange={onShowSizeChange}
                onChange={onChangePageNum}
                defaultCurrent={1}
                pageSize={pageSize}
                total={total}
                />
            </div>
        </div>
    )
}